package system

import (
	"errors"
	"fmt"
	"k8s-admin/global"
	"k8s-admin/models"
	"k8s-admin/utils"
	"time"
)

type UsersInterface interface {
	List(Limie, Page int) (*models.UserList, error)
	Create(username, password, Phone, Email string, roles []uint, status, dept_id uint) (*models.User, error)
	Delete(UID string) error
	Update(uid, username, password, email, phone string, status uint, roles_id []uint) error
	GetUserFromUserName(uid string) (*models.User, error) // 用户权限查询
	SetUserRole(roleID []uint, uid string) error
	DeleteUserRole(roleID []uint, uid string) error // 删除用户角色

}

type UsersInfo struct{}

func NewUsersInterface() UsersInterface {
	return &UsersInfo{}
}

func (i *UsersInfo) List(Limit, Page int) (*models.UserList, error) {
	userList := []*models.User{}
	var Count int64
	tx := global.GORM.Model(&models.User{}).Count(&Count).Preload("Dept").Preload("Roles").Offset((Limit - 1) * Page).Limit(Page).Find(&userList)
	if tx.Error != nil {
		return nil, tx.Error
	} else if tx.RowsAffected == 0 {
		return nil, errors.New("没有数据")
	} else {
		return &models.UserList{
			Items: userList,
			Total: Count,
		}, nil
	}
}

func (i *UsersInfo) Create(username, password, Phone, Email string, roles []uint, status, dept_id uint) (*models.User, error) {
	var role []models.Role
	err := global.GORM.Where("id IN ?", roles).Find(&role).Error
	if err != nil {
		return nil, err
	} else {
		uid := utils.GemSnowFlask(username)
		user := &models.User{
			UID:       uid,
			Username:  username,
			Password:  password,
			Phone:     Phone,
			Email:     Email,
			Status:    status,
			Roles:     role,
			DeptId:    dept_id,
			CreatedAt: time.Now().Format(time.DateTime),
			UpdatedAt: time.Now().Format(time.DateTime),
		}
		err := global.GORM.Create(&user).Error
		if err != nil {
			return nil, err
		} else {
			return user, nil
		}
	}

}

func (i *UsersInfo) Delete(UID string) error {
	// 删除用户并同时删除用户角色关联关系
	err := global.GORM.Unscoped().Model(&models.User{UID: UID}).Association("Roles").Unscoped().Clear() // 清理关联关系
	if err != nil {
		return err
	} else {
		tx := global.GORM.Model(&models.User{}).Where("uid=?", UID).Delete(&models.User{})
		if tx.Error != nil {
			return err

		} else if tx.RowsAffected == 0 {
			return errors.New("删除失败，该用户不存在")
		} else {
			return nil
		}
	}
}

func (i *UsersInfo) Update(uid, username, password, email, phone string, status uint, roles_id []uint) error {
	fmt.Println("status: ", status)

	tx := global.GORM.Model(&models.User{}).Where("uid=?", uid).Updates(map[string]interface{}{
		"username": username, "password": password, "phone": phone, "email": email, "status": status, "updated_at": time.Now().Format(time.DateTime),
	})
	if tx.Error != nil {
		return tx.Error
	} else if tx.RowsAffected == 0 {
		return errors.New("更新失败，没有对应的用户数据")
	} else {
		var roles []models.Role
		global.GORM.Where("id IN ?", roles_id).Find(&roles)
		err := global.GORM.Model(&models.User{
			UID: uid,
		}).Association("Roles").Replace(&roles)
		if err != nil {
			return err
		} else {
			return nil
		}
	}

}

// 用户权限查询
func (i *UsersInfo) GetUserFromUserName(uid string) (*models.User, error) {
	user := &models.User{}
	err := global.GORM.Where("uid = ?", uid).Preload("Roles").Preload("Dept").First(&user).Error
	if err != nil {
		return nil, err
	} else {
		return user, nil
	}
}

// 赋权
func (i *UsersInfo) SetUserRole(roleID []uint, uid string) error {
	var role []models.Role
	user := models.User{
		UID: uid,
	}

	err := global.GORM.Where("id IN ?", roleID).Find(&role).Error
	if err != nil {
		return err
	} else {
		// 将角色赋给已存在的用户
		err := global.GORM.Model(&user).Association("Roles").Replace(role)

		if err != nil {
			return err
		} else {
			return nil
		}
	}

}
func (i *UsersInfo) DeleteUserRole(roleID []uint, uid string) error {
	var Roles []models.Role
	err := global.GORM.Where("id IN ?", roleID).Find(Roles).Error
	if err != nil {
		return err
	} else {
		err = global.GORM.Model(&models.User{UID: uid}).Association("Roles").Delete(Roles)
		if err != nil {
			return err
		} else {
			return nil
		}
	}
}
